#include"spi.h"

void spi_init(void)
{
    //开启时钟 
    RCC->APB2ENR|=RCC_APB2ENR_IOPAEN;
    RCC->APB2ENR|=RCC_APB2ENR_IOPDEN;
    RCC->APB1ENR|=RCC_APB1ENR_SPI2EN;
    RCC->APB2ENR|=RCC_APB2ENR_IOPBEN;
    RCC->APB2ENR|=RCC_APB2ENR_IOPGEN;

    //配置GPIO PB15   复用推挽输出 MODE 11 CNF 10      PB14 浮空输入 MODE 00 CNF 01   片选PD3 通用推挽输出 mode 11 cnf 00
    GPIOB->CRH|=(GPIO_CRH_MODE15|GPIO_CRH_MODE13);
    GPIOB->CRH|=(GPIO_CRH_CNF15_1|GPIO_CRH_CNF13_1);
    GPIOB->CRH&=~(GPIO_CRH_CNF15_0|GPIO_CRH_CNF13_0);

    GPIOD->CRL|=GPIO_CRL_MODE3;
    GPIOD->CRL&=~GPIO_CRL_CNF3;

    GPIOB->CRH&=~GPIO_CRH_MODE14;
    GPIOB->CRH&=~GPIO_CRH_CNF14;
    GPIOB->CRH|=GPIO_CRH_CNF14_0;

    //配置SPI
    //配置为主模式
    SPI2->CR1|=SPI_CR1_MSTR;

    //配置软件片选
    SPI2->CR1|=SPI_CR1_SSM;
    SPI2->CR1|=SPI_CR1_SSI;

    //分频
    SPI2->CR1&=~SPI_CR1_BR;
    //模式0
    SPI2->CR1&=~SPI_CR1_CPHA;
    SPI2->CR1&=~SPI_CR1_CPOL;

    //高位先行
    SPI2->CR1&=~SPI_CR1_LSBFIRST;

    //8位数据帧格式
    SPI2->CR1&=~SPI_CR1_DFF;

    //使能
    SPI2->CR1|=SPI_CR1_SPE;

}

void spi_start(void)
{
    SPI_CS_LOW;

}

void spi_stop(void)
{
    SPI_CS_HIGH;

}

uint8_t spi_swapdata(uint8_t data)
{
    while ((SPI2->SR & SPI_SR_TXE)==0)
    {
    }
    SPI2->DR=data;

    while ((SPI2->SR & SPI_SR_RXNE)==0)
    {
    }
    
    return (uint8_t)(SPI2->DR);
    
}
